/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */
import {message} from 'ss-components';

export function onPropsReceive({key, nextProps, loading, success, successAlert = false, fail, failAlert = false}) {
  if (this.props[key] === nextProps[key]) {
    return;
  }
  let prop = nextProps[key];
  if (prop.loading) {
    let state = loading ? loading() : {loading: true};
    if (state) {
      this.setState(state);
    }
  } else if (prop.success) {
    let state = success ? success(prop) : {loading: false};
    if (state) {
      successAlert && message.success('操作成功', 3);
      this.setState(state);
    }
  } else if (!prop.success) {
    let state = fail ? fail(prop) : {loading: false};
    if (state) {
      failAlert && message.error(prop.error || '操作失败', 3);
      this.setState(state);
    }
  }
}

export function shouldUpdate(nextProps, nextState) {
  return Object.keys(nextProps || {}).some((prop) => nextProps[prop] !== this.props[prop])
    || Object.keys(nextState || {}).some((state) => nextState[state] !== this.state[state]);
}
